package com.hongyi.modelcontest.core.util;

import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SMSUtils {
    private static final Logger logger = LoggerFactory.getLogger(SMSUtils.class);

    // 短信应用SDK AppID
    // 1400开头
    private static final int APPID = 1400190711;
    /**
     * appkey
     */
    private static final String APPKEY = "f9a63c6a64700afef9e94240e988c152";
    // 签名
    private static final String SMS_SIGN = "我就是超模";


    /**
     * 发送验证码
     * spring.mail.pass
     */
    public static void shouli(String phoneNumber, String code) {
        //数组具体的元素个数和模板中变量个数必须一致，例如事例中templateId:5678对应一个变量，参数数组中元素个数也必须是一个
        String[] params = {code};
        int templateId = 287321;
        SmsSingleSender ssender = new SmsSingleSender(APPID, APPKEY);
        try {
            // 签名参数未提供或者为空时，会使用默认签名发送短信
            SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumber,
                    templateId, params, SMS_SIGN, "", "");
            if (result.result != 0) {
                throw new ServiceException(500, result.errMsg);
            }
        } catch (HTTPException | IOException e) {
            logger.error("发送短信失败:{}", e);
            throw new ServiceException(500, e.getMessage());
        }
    }
}